package no.evalanche.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.json.JSONException;
import org.json.JSONObject;

import android.net.http.AndroidHttpClient;
import android.os.Handler;
import android.util.Log;

public class ResultsGraphicsIO  extends MC_Async {
	

	public ResultsGraphicsIO(String s, Handler h) {
		sessionid = s;
		handler = h;
	}

	@Override
	protected JSONObject doInBackground(EntityList... pams) {
		JSONObject jsonobject = null;
		AndroidHttpClient httpclient = AndroidHttpClient.newInstance("android");
		HttpPost request = new HttpPost(ServiceList.URL.toString());
		request.setHeader("Cookie","sessionid="+sessionid);
		try {  
			request.setEntity(new UrlEncodedFormEntity(pams[0]));
			HttpResponse r = httpclient.execute(request);
			jsonobject = jsonFromEntity(r);			
			httpclient.close();
		} catch (IOException e) {
			Log.d("EvalancheAuthenticator",
					"Feil i doInBackground! " + e.toString());
		}
		return jsonobject;
	}

	
	private JSONObject jsonFromEntity(HttpResponse r) throws IOException {
		HttpEntity httpEntity = r.getEntity();
		BufferedReader br = new BufferedReader(new InputStreamReader(
				httpEntity.getContent()));
		String line;
		StringBuilder builder = new StringBuilder();
		while ((line = br.readLine()) != null) {
			builder.append(line);
		}
		try {
			return new JSONObject(builder.toString());
		} catch (JSONException e) {
			return new JSONObject();
		}
	}
	
	
}
